package forum.dao.util;

import forum.entities.Entity;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class EntityValidator {
    private static ValidatorFactory vf = Validation.buildDefaultValidatorFactory();

    public static void validate(Entity entity) {
        Set<ConstraintViolation<Entity>> constraintViolations = vf.getValidator().validate(entity);
        StringBuilder reportBuilder = new StringBuilder();
        for (ConstraintViolation<Entity> cv : constraintViolations) {
            reportBuilder.append(cv.getInvalidValue());
            reportBuilder.append(" -- ");
            reportBuilder.append(cv.getMessage());
            reportBuilder.append(System.lineSeparator());
        }
        if (constraintViolations.size() != 0) {
            throw new IllegalArgumentException(reportBuilder.toString());
        }
    }
}
